from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import GepResult
from app.utils.decorators import admin_required

gep_results_bp = Blueprint('gep_results', __name__)

@gep_results_bp.route('/', methods=['GET'])
@jwt_required()
@admin_required
def get_gep_results():
    """获取GEP结果列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取搜索参数
    gep_year = request.args.get('gepYear', '')
    gep_city = request.args.get('gepCity', '')
    gep_district = request.args.get('gepDistrict', '')
    gep_town = request.args.get('gepTown', '')
    
    query = GepResult.query
    
    # 根据搜索条件过滤
    if gep_year:
        query = query.filter(GepResult.year == gep_year)
    if gep_city:
        query = query.filter(GepResult.gepCity.contains(gep_city))
    if gep_district:
        query = query.filter(GepResult.gepDistrict.contains(gep_district))
    if gep_town:
        query = query.filter(GepResult.gepTown.contains(gep_town))
    
    # 限制最多返回100条数据
    total_count = query.count()
    if total_count > 100:
        # 如果总数超过100，调整分页参数
        per_page = min(per_page, 100)
        page = min(page, (total_count + per_page - 1) // per_page)
    
    pagination = query.paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    results = pagination.items
    
    return jsonify({
        'gep_results': [result.to_dict() for result in results],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': min(pagination.total, 100),
            'pages': pagination.pages
        }
    }), 200

@gep_results_bp.route('/<int:result_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_gep_result(result_id):
    """获取单个GEP结果详情"""
    result = GepResult.query.get(result_id)
    if not result:
        return jsonify({'message': '结果不存在'}), 404
    
    return jsonify({
        'gep_result': result.to_dict()
    }), 200

@gep_results_bp.route('/', methods=['POST'])
@jwt_required()
@admin_required
def create_gep_result():
    """创建GEP结果"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['year', 'gepCity', 'gepDistrict', 'gepTown']
    for field in required_fields:
        if not data.get(field):
            return jsonify({'message': f'字段 {field} 不能为空'}), 400
    
    # 检查唯一性约束
    existing = GepResult.query.filter_by(
        year=data['year'],
        gepCity=data['gepCity'],
        gepDistrict=data['gepDistrict'],
        gepTown=data['gepTown']
    ).first()
    
    if existing:
        return jsonify({'message': '该地区该年份的GEP项目结果已存在'}), 400
    
    # 创建新结果
    result = GepResult(
        year=data['year'],
        gepCity=data['gepCity'],
        gepDistrict=data['gepDistrict'],
        gepTown=data['gepTown'],
        gepResult=data.get('gepResult'),
        materialSupplyValue=data.get('materialSupplyValue'),
        cleanEnergyValue=data.get('cleanEnergyValue'),
        waterResourcesValue=data.get('waterResourcesValue'),
        tourismHealthValue=data.get('tourismHealthValue'),
        leisureRecreationValue=data.get('leisureRecreationValue'),
        landscapeAppreciationValue=data.get('landscapeAppreciationValue'),
        creator=str(current_user_id)
    )
    
    try:
        db.session.add(result)
        db.session.commit()
        return jsonify({
            'message': '创建成功',
            'gep_result': result.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建失败: {str(e)}'}), 500

@gep_results_bp.route('/<int:result_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_gep_result(result_id):
    """更新GEP结果"""
    current_user_id = get_jwt_identity()
    result = GepResult.query.get(result_id)
    
    if not result:
        return jsonify({'message': '结果不存在'}), 404
    
    data = request.get_json()
    
    # 允许更新的字段
    allowed_fields = [
        'gepResult', 'materialSupplyValue', 'cleanEnergyValue', 'waterResourcesValue',
        'tourismHealthValue', 'leisureRecreationValue', 'landscapeAppreciationValue'
    ]
    
    # 更新字段
    for field in allowed_fields:
        if field in data:
            setattr(result, field, data[field])
    
    result.updater = str(current_user_id)
    
    try:
        db.session.commit()
        return jsonify({
            'message': '更新成功',
            'gep_result': result.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新失败: {str(e)}'}), 500

@gep_results_bp.route('/<int:result_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_gep_result(result_id):
    """删除GEP结果"""
    result = GepResult.query.get(result_id)
    
    if not result:
        return jsonify({'message': '结果不存在'}), 404
    
    try:
        db.session.delete(result)
        db.session.commit()
        return jsonify({'message': '删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除失败: {str(e)}'}), 500 